'use strict';
var  fs = require('fs');
var cache = require('./patient_cache');
var utils = require('./common_utils');

var NUMBER_OF_RESULTS = 50;

//////////////////////////// PATIENTS

var parseRequest = function (req) 
{
//	console.log(" parseRequest  ");
	if (req && req.body) {
		return req.body;
	}
	return null;
}

// GET

exports.getAllPatients = function(req,res) {

	console.log("\n\n DEBUG-api: getAllPatients ")

	try {

//		var patientIndex = parseRequest(req);
		var inputData = parseRequest(req);
		var filteredList = cache.data.patients;
		if (filteredList.length > 0) {
			if (inputData) {
				console.log(inputData)
				filteredList = cache.getFilteredPatientList(inputData.data.split(","));
			}
			filteredList = filteredList.slice(0,NUMBER_OF_RESULTS);
			if(res) res.json(filteredList);
			return;
		}
	
		filteredList = cache.browseAllPatientFolders().slice(0,NUMBER_OF_RESULTS);
		console.log("getAllPatients - READ: #" + cache.data.patients.length+ " patients");
		
		if(res) res.json(filteredList);
	}
	catch (err) {
		console.log("Error occurred while reading file "+err);
		if(res) res.send(404);
	}
}


/* *
 * Mehtode pour la lecture des patients dans le file system
 * @params: /:name/:surname/:id
 */
exports.getPatient = function(req,res) {

	console.log("\n\n DEBUG-api: getPatient ")

	try {
		var patientJson = parseRequest(req);
		utils.open(utils.PATIENTS_FOLDER, patientJson.nom, patientJson.prenom, patientJson.id, function(status,data){
			if (status == 200) {
				res.json(data);
			}
			else {
				res.send(status);
			}
		});
	}
	catch (err) {
		console.log("Error occurred while reading file "+err);
		res.send(404);
	}
}


// POSTS
exports.updatePatient = function(req,res) {

	console.log("\n\n DEBUG-api: updatePatient ")
	
	try {
		var patientJson = parseRequest(req);
		var patientIndex = cache.getJsonIndexForPatient(patientJson.nom, patientJson.prenom, patientJson.id);
		
		utils.save(patientJson,utils.PATIENTS_FOLDER,patientJson.nom, patientJson.prenom, patientJson.id,function(status){
			if (status==200) {
				cache.updatePatient(patientIndex);
				res.json(patientIndex);
			}
			else {
				res.send(status);
			}
		});

	}
	catch (err) {
		console.log("Error occurred while saving file "+err);
		res.send(404);
	}
}

//DELETE
exports.deletePatient = function(req,res) {

	console.log("\n\n DEBUG-api: deletePatient ");

	try {
		var patientIndex = parseRequest(req);
		utils.delete(patientIndex.path,function(status) {
			if (status == 200) {
				res.send(cache.removePatient(patientIndex)?200:404);
			}
			else {
				console.log(patientIndex.path+" cannot be removed");
				res.send(404);
			}
		});
		
	}
	catch (err) {
		console.log("Error occurred while removing file "+err);
		res.send(404);
	}
}